import fs from 'fs';
import { resolve, basename, dirname } from 'node:path';
import { globSync } from 'glob';
import styles from 'rollup-plugin-styles';
import { swc } from 'rollup-plugin-swc3';
import monacoLocaleInject from './rollup-plugin-monaco-locale-inject.js';

/**
 * @type {Partial<import('rollup').RollupOptions>}
 */
const rollupCommonOptions = {
  context: 'window',
};

/**
 * @type {import('rollup-plugin-styles').Options}
 */
const stylesOptions = {};

/**
 * @type {import('rollup-plugin-swc3').PluginOptions}
 */
const swcOptions = {
  minify: true,
};

const entryPrefix = './node_modules/monaco-editor/esm/vs';

const outputDir = resolve('./dist');

const joinPath = (...segments) => segments.filter(Boolean).join('/');

const rmdir = dir =>
  dir &&
  fs.existsSync(dir) &&
  fs.statSync(dir).isDirectory() &&
  fs.rmSync(dir, { recursive: true });

const makeWorkerUmdName = name => `monaco-${name}-worker`;

const languageEntries = globSync(`${entryPrefix}/language/**/*.worker.js`).map(
  it => ({
    ...rollupCommonOptions,
    input: it,
    output: {
      file: joinPath(outputDir, `${basename(it)}`),
      name: makeWorkerUmdName(basename(dirname(it))),
      format: 'umd',
    },
    context: 'window',
    plugins: [monacoLocaleInject(), swc(swcOptions)],
  }),
);

export default [
  {
    ...rollupCommonOptions,
    input: `${entryPrefix}/editor/editor.main.js`,
    output: {
      // dir: outputDir,
      file: joinPath(outputDir, 'monaco-editor.js'),
      name: 'monaco',
      format: 'umd',
      inlineDynamicImports: true,
      assetFileNames: '[name][extname]',
    },
    plugins: [
      rmdir(outputDir),
      monacoLocaleInject(),
      styles(stylesOptions),
      swc(swcOptions),
    ],
  },
  {
    ...rollupCommonOptions,
    input: `${entryPrefix}/editor/editor.worker.js`,
    output: {
      file: joinPath(outputDir, 'editor.worker.js'),
      name: makeWorkerUmdName('editor'),
      format: 'umd',
    },
    plugins: [monacoLocaleInject(), swc(swcOptions)],
  },
  ...languageEntries,
];
